<template>
  <div class="mod-config">
    <el-form ref="form" :inline="true" label-width="80px">
      <el-form-item width="400px">
        <el-input placeholder="输入名称搜索相关内容" v-model="condition" clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-upload
          action="http://121.41.167.195:8089/renren-fast/sf/copybookCharacter/copybookResource/upload"
          :accept="'application/zip'"
          :before-upload="beforeZipUpload"
          :on-success="handleZipSuccess"
          :on-error="handleZipError"
          name="copybookResourceZip"
          :show-file-list="false">
          <el-button slot="trigger" type="primary">批量资源上传</el-button>
        </el-upload>
      </el-form-item>
      <el-button type="primary" @click="addScript()">添加字帖字</el-button>
      <el-button type="info" @click="downtemplate()">下载资源模板</el-button>
      <el-button type="danger" v-show="showMoveBtn1" @click="multipledeleteHandle(true)">批量删除字帖字</el-button>
      <el-button type="danger" v-show="showMoveBtn2" @click="multipledeleteHandle(false)">批量删除字帖字信息</el-button>
    </el-form>

    <el-table :data="dataScriptList" stripe v-loading="dataListLoading" style="width: 100%"
      @selection-change="handleSelectionChange(true,$event)" @expand-change="expandSelect" :row-key='getRowKeys'
      :expand-row-keys="expands">
      <el-table-column prop="" type="selection" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table label-position="left" :data="props.row.coChrInformationList" inline class="demo-table-expand"
            @selection-change="handleSelectionChange(false,$event)">
            <el-table-column prop="" type="selection" />
            <el-table-column label="字帖字id" prop="id"></el-table-column>
            <el-table-column label="字帖字信息Src" align="center">
              <template slot-scope="scope">
                <i v-show="isLoading" class="el-icon-loading" style="font-size: 40px;"></i>
                <el-image v-show="!isLoading" :src="scope.row.copybookCharacter" @load="handleImgLoadZi()">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="字体" prop="characterType" align="center"></el-table-column>
            <el-table-column label="书家" prop="calligrapher" align="center"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="modifyScriptZiInfo(scope.row)">修改字信息</el-button>
                </el-button>
                <el-button type="text" size="small" @click="deleteZiHandle(scope.row)">删除字信息</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="字帖字id"></el-table-column>
      <el-table-column prop="copybookCharacterName" label="字帖字名称"></el-table-column>
      <el-table-column prop="createtime" label="创建时间"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openScriptInfo(scope.row)">添加字帖字信息</el-button>
          </el-button>
          <el-button type="text" size="small" @click="AddScriptZi(scope.row)">修改字帖字</el-button>
          </el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除字帖字</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 新增字帖字信息模态框 -->
    <el-dialog :title=isStatusName :visible.sync="dialogScriptZiInfoVisible" width="1000px" destroy-on-close
      v-loading="dialogLoading">
      <el-form :model="scriptZiInfoDataForm" ref="scriptZiInfoForm" :rules="rules"
        @keyup.enter.native="dataFormSubmit()" label-width="100px">
        <el-form-item label="字帖字信息Src" prop="copybookCharacter" label-width="150px">
          <div class="motaikuang">
            <el-upload action="http://121.41.167.195:8000/api/oss/upload" :show-file-list="false" ref="uploadForm"
              :on-success="handleAvatarSuccess" :on-remove="handleRemove" :limit=1 :before-upload="beforeAvatarUpload"
              :on-exceed="exceedPic">
              <img v-if="imageUrl" :src="scriptZiInfoDataForm.copybookCharacter" class="avatar"
                style="border: 1px dashed #d9d9d9;">
              <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 70px;"></i>
            </el-upload>
            <i v-if="imageUrl" class="el-icon-delete delIcon" @click.stop="delPic()" />
          </div>
          <div>只能上传jpg/png文件，且不超过10MB</div>
        </el-form-item>
        <el-form-item label="字体" prop="characterTypeId" label-width="150px">
          <el-select v-model="scriptZiInfoDataForm.characterTypeId" placeholder="请选择字体">
            <el-option v-for="item in styleOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书家" prop="calligrapherId" label-width="150px">
          <el-select v-model="scriptZiInfoDataForm.calligrapherId" placeholder="请选择书家">
            <el-option v-for="item in shuOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="doAdd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        dataScriptList: null,

        isAdd: true,
        tag: 'years',

        condition: '',
        shuOptions: [],
        styleOptions: [],
        dialogLoading: false,
        dialogImageUrl: '',
        dialogVisible: false,
        imageUrl: null,
        scriptZiInfoDataForm: {
          copybookCharacter: null,
          characterTypeId: null,
          calligrapherId: null,
          cid: null,
        },
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        isLoading: true,
        rules: {
          copybookCharacter: [{
            required: true,
            message: '请上传字帖字封面',
            trigger: 'change'
          }],
          characterTypeId: [{
            required: true,
            message: '请选择字体',
            trigger: 'change'
          }],
          calligrapherId: [{
            required: true,
            message: '请上传书家',
            trigger: 'change'
          }],
        },

        dialogScriptZiInfoVisible: false,
        showMoveBtn: false,
        expands: [], //只展开一行放入当前行id
        getRowKeys(row) { //设置row-key只展示一行
          return row.id
        },
        multipleSelection1:[],
        multipleSelection2:[],
        showMoveBtn1:false,
        showMoveBtn2:false,
      }
    },
    components: {},
    created() {
      this.getScriptDataList()
    },
    watch: {
      condition: {
        handler(newValue, OldValue) {
          this.getScriptDataList()
          this.pageIndex = 1
        }
      },
      dialogScriptZiInfoVisible: {
        handler(newValue, OldValue) {
          this.getCopybookStyle()
          this.getCopybookShu()
        }
      },
    },
    computed: {
      isStatusName: function() {
        if (this.isAdd) {
          return '新增字帖字信息'
        } else {
          return '修改字帖字信息'
        }
      },
    },
    methods: {
      // --------------------这是字帖字代码----------------------------
      // 获取字帖字列表
      getScriptDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl("/sf/copybookCharacter/copybookCharacter/list"),
          method: "post",
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: this.$http.adornData({
            coChrName: this.condition,
            curPage: this.pageIndex,
            pageSize: this.pageSize,
          }, true, 'form')
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataScriptList = data.data.record;
            this.totalPage = data.data.total;
          } else {
            this.$message.error(data.message);
            this.dataScriptList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
          this.multipleSelection1 = []
          this.multipleSelection2 = []
        });
      },
      // 新增 -- 字帖字框
      addScript() {
        this.$prompt('请输入名称', '添加字帖字', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({
          value
        }) => {
          if (!value){
            this.$message({
              type: 'info',
              message: '输入为空'
            })
            return false
          }
          this.dataListLoading = true
          this.$http({
            url: this.$http.adornUrl("/sf/copybookCharacter/copybookCharacter/save"),
            method: "post",
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: this.$http.adornData({
              copybookCharacterName: value,
            }, true, 'form'),
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getScriptDataList()
                },
              });
            } else {
              this.$message.error(data.msg);
            }
            this.dataListLoading = false
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消添加'
          })
        })
      },
      //打开字帖信息框
      openScriptInfo(row) {
        this.isAdd = true
        this.dialogScriptZiInfoVisible = true
        this.scriptZiInfoDataForm = {
          copybookCharacter: null,
          characterTypeId: null,
          calligrapherId: null,
          cid: null,
        }
        this.scriptZiInfoDataForm.cid = row.id
        this.imageUrl = null
      },
      // 获得字体 书家数据
      getCopybookStyle() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl("/sf/copybookCharacter/cc/get"),
          method: "get",
          params: this.$http.adornParams({
            type: 1
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.styleOptions = data.data.map(item => {
              return {
                label: item.characterType,
                value: item.id
              }
            });

          } else {
            this.$message.error(data.message);
            this.styleOptions = [];
          }
          this.dataListLoading = false;
        });
      },
      getCopybookShu() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl("/sf/copybookCharacter/cc/get"),
          method: "get",
          params: this.$http.adornParams({
            type: 2
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.shuOptions = data.data.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            });

          } else {
            this.$message.error(data.message);
            this.shuOptions = [];
          }
          this.dataListLoading = false;
        });
      },
      // 上传字帖字封面
      handleAvatarSuccess(res, file) {
        this.dialogLoading = false
        this.imageUrl = res.url;
        this.scriptZiInfoDataForm.copybookCharacter = res.url;
      },
      beforeAvatarUpload(file) {
        this.dialogLoading = true
        const isJPG = file.type === 'image/jpeg' || 'png';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 或PNG格式!');
          this.dialogLoading = false
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
          this.dialogLoading = false
        }

        return isJPG && isLt2M;
      },
      // 删除图片
      handleRemove(file, fileList) {
        this.scriptZiInfoDataForm.copybookCharacter = null
        this.imageUrl = null
      },
      // 上传超出数量
      exceedPic() {
        this.$message.error('只能上传一张封面')
      },
      // 年代书法框--取消按钮
      cancelAdd() {
        this.isLoading = true
        this.dialogScriptZiInfoVisible = false
      },
      // 字帖字模态框--提交确定按钮
      doAdd() {
        this.$refs['scriptZiInfoForm'].validate((valid) => {
          if (valid) {
            this.dialogLoading = true
            this.$http({
              url: this.$http.adornUrl(
                `/sf/copybookCharacter/copybookInfor//${this.isAdd?"save":"update"}`),
              method: "post",
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              data: this.$http.adornData(this.scriptZiInfoDataForm, true, 'form')
            }).then(({
              data
            }) => {
              this.dialogLoading = false
              if (data && data.code === 0 && data.success == true) {

                this.$message({
                  message: `${this.isAdd?'新增成功':'更新成功'}`,
                  type: "success",
                  duration: 1000,
                  onClose: () => {
                    this.dialogScriptZiInfoVisible = false

                    this.getScriptDataList()
                  },
                });
              } else {
                this.$message.error(data.message);
              }
            });
          } else {
            this.dataListLoading = false
            console.log('error submit!!')
            return false
          }
        })

      },
      // 修改--打开书法框
      modifyScriptZiInfo(row) {
        this.dialogScriptZiInfoVisible = true
        this.$nextTick(() => {
          this.isAdd = false
          this.imageUrl = row.copybookCharacter;
          let yid = ''
          let sid = ''
          // 遍历下拉框的选项，寻找需要选中的选项
          for (let i = 0; i < this.styleOptions.length; i++) {
            if (this.styleOptions[i].label == row.characterType) { // 假设需要选中的是“选项2”
              yid = this.styleOptions[i].value; // 将选项2的value设置为v-model绑定的值
              break;
            }
          }
          // 遍历下拉框的选项，寻找需要选中的选项
          for (let i = 0; i < this.shuOptions.length; i++) {
            if (this.shuOptions[i].label == row.calligrapher) { // 假设需要选中的是“选项2”
              sid = this.shuOptions[i].value; // 将选项2的value设置为v-model绑定的值
              break;
            }
          }
          this.scriptZiInfoDataForm = {
            id: row.id,
            copybookCharacter: row.copybookCharacter,
            characterTypeId: yid,
            calligrapherId: sid,
            cid: row.cid,
          }
        })
      },
      // 展开行变化时触发
      expandSelect(row, expandedRows) {
        //加载前先将上次的数据模型情况，不然会出现点击展开嵌套表格后，先显示上一次的数据，然后渲染这次的数据。
        this.observe = [];
        //只展开一行
        if (expandedRows.length) { //说明展开了
          this.expands = [];
          if (row) {
            this.expands.push(row.id); //只展开当前行id
          }
        } else { //说明收起了
          this.expands = [];
        }
      },
      // 删除
      deleteHandle(row) {
        this.$confirm(`确定对id[${row.id}]进行[删除]操作?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.dataListLoading = true
            this.$http({
              url: this.$http.adornUrl("/sf/copybookCharacter/copybookCharacter/delete"),
              method: "post",
              data: this.$http.adornData([row.id], false),
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getScriptDataList()
                  },
                });
              } else {
                this.dataListLoading = false
                this.$message.error(data.message);
              }
            });
          })
          .catch(() => {});
      },

      // 打开字帖字弹框
      AddScriptZi(row) {
        this.$prompt('请输入名称', '修改字帖字', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({
          value
        }) => {
          if (!value){
            this.$message({
              type: 'info',
              message: '输入为空'
            })
            return false
          }
          this.dataListLoading = true
          this.$http({
            url: this.$http.adornUrl("/sf/copybookCharacter/copybookCharacter/update"),
            method: "post",
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: this.$http.adornData({
              copybookCharacterName: value,
              id: row.id
            }, true, 'form'),
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getScriptDataList()
                },
              });
            } else {
              this.$message.error(data.msg);
            }
            this.dataListLoading = false
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消添加'
          })
        })

      },
      // 关闭字帖字字弹框
      cancelAddZi() {
        this.dialogScriptZiInfoVisible = false
      },
      //字帖字字模态框---提交确定按钮
      doAddZi() {
        this.dialogLoading = true
        let dataArray = this.productForm.productPicList.map(item => {
          return {
            sid: this.scriptZiInfoDataForm.id,
            steleCalligraphyCharacter: item
          }
        })
        this.$http({
          url: this.$http.adornUrl("/sf/copyingSteleCalligraphy/stelecallicharacter/updatesave"),
          method: "post",
          data: dataArray
        }).then(({
          data
        }) => {
          this.dialogLoading = false
          if (data && data.code === 0 && data.success == true) {

            this.$message({
              message: "更新成功",
              type: "success",
              duration: 1000,
              onClose: () => {
                this.dialogScriptZiInfoVisible = false
                this.getScriptDataList()
              },
            });
          } else {
            this.$message.error(data.message);
          }
        });
      },
      // 图片未渲染加载
      handleImgLoadZi() {
        this.isLoading = false
      },
      delPic() {
        this.$refs.uploadForm.clearFiles()
        this.scriptZiInfoDataForm.copybookCharacter = null
        this.imageUrl = null
      },
      // --------------------这是分页公共代码----------------------------
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getScriptDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getScriptDataList()
      },


      // 点击多选框事件
      handleSelectionChange(type, val) {
        if (type) {
          this.multipleSelection1 = val
          this.showMoveBtn1 = this.multipleSelection1.length != 0
        } else {
          this.multipleSelection2 = val
          this.showMoveBtn2 = this.multipleSelection2.length != 0
        }
      },
      // 删除多个文件
    multipledeleteHandle(type) {
        const ids = []
        let flag = ''
        if (type) {
          this.multipleSelection1.forEach(item => {
            ids.push(item.id)
          })
          flag = 'copybookCharacter'
        } else {
          this.multipleSelection2.forEach(item => {
            ids.push(item.id)
          })
          flag = 'copybookInfor'
        }
        this.$confirm(`确定对这些进行[删除]操作?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl(`/sf/copybookCharacter/${flag}/delete`),
              method: "post",
              data: this.$http.adornData(ids, false),
            }).then(({
              data
            }) => {
              if (data && data.code === 0 && data.success) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getScriptDataList()()
                  },
                });
              } else {
                this.getScriptDataList()
                this.$message.error(data.message);
              }
            });
          })
          .catch(() => {});
      },
      // 删除字信息
      deleteZiHandle(row){
       this.$confirm(`确定对id[${row.id}]进行[删除]操作?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.dataListLoading = true
            this.$http({
              url: this.$http.adornUrl("/sf/copybookCharacter/copybookInfor/delete"),
              method: "post",
              data: this.$http.adornData([row.id], false),
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getScriptDataList()
                  },
                });
              } else {
                this.dataListLoading = false
                this.$message.error(data.message);
              }
            });
          })
          .catch(() => {});
      },
      // 下载资源模板
      downtemplate(){
        // 创建一个 <a> 元素
        this.$message.info('资源下载中')
        const link = document.createElement('a');
        link.href = ' https://anhuihanzhi-shufa-client.oss-cn-hangzhou.aliyuncs.com/2023/07/29ccedc345d9a64fa8957808cb81de74fd字帖资源模板.zip'; // 替换为你的 ZIP 文件的路径

        // 设置下载的文件名
        link.download = '字帖资源模板.zip'; // 替换为你想要的文件名

        // 模拟点击下载链接
        link.click();
      },
      beforeZipUpload(file){
        const maxSize = 300 * 1024 * 1024; // 300MB
        if (file.size > maxSize) {
          this.$message.error('文件尺寸超过限制，请选择不超过300MB大小的Zip文件');
          return false; // 阻止上传
        }
        this.$message.info('文件上传中！');
        return true; // 允许上传
      },
      handleZipSuccess(){
      // 处理上传成功的逻辑
          this.$message.success('文件上传成功！');
      },
      handleZipError(){
      // 处理上传成功的逻辑
      this.$message.error('文件上传失败！');
      }
    },
  };
</script>
<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }


  .imgSty {
    width: 148px;
    height: 148px;
  }

  .delIcon {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 40px;
  }

  .uploadIcon {
    margin-left: 40px;
  }

  .motaikuang {
    width: 150px;
    height: 150px;
    position: relative;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
  }

  .delIcon {
    position: absolute;
    right: -50px;
    bottom: 0px;
    font-size: 40px;
    cursor: pointer;
  }
</style>
